#! /usr/bin/env python
# encoding: utf-8
from __future__ import print_function

from argparse import ArgumentParser
import os
import re
import requests
__author__ = "HuangJacky"
reg_url = re.compile('(https:\/\/fonts\.gstatic\.com\/s\/([^\'")]+))', re.I)


def main():
    parser = ArgumentParser(description="Google字体下载", version="1.0.0")
    parser.add_argument('-d', '--dir', dest='dir', help="字体下载目录，一般推荐是Web网站的字体目录下", required=True)
    parser.add_argument('-u', '--url', dest='url', help='远端原始CSS的地址',required=False, default='')
    parser.add_argument('-f', '--file', dest='file', help='本地原始CSS的地址',required=False, default='')
    args = parser.parse_args()
    soucecode = ''
    if os.path.exists(args.dir):
        if not os.path.isdir(args.dir):
            print("请设置一个合法的目录")
            parser.print_help()
    else:
        os.mkdir(args.dir)
    #
    if args.file == '' and args.url == '':
        parser.print_usage()
        return
    if args.file and os.path.exists(args.file):
        f = open(args.file, 'r')
        soucecode = f.read()
        f.close()
    elif args.url:
        try:
            r = requests.get(args.url)
            if r.status_code == 200:
                soucecode = r.content
        except Exception as e:
            print(e.message)
            print('网络请求异常，请检查url参数')
            parser.print_usage()
            return
    else:
        print('输入参数有误')
        parser.print_help()
        return
    #
    ret = reg_url.findall(soucecode)
    for r in ret:
        print(r)
        url = r[0]
        fp = os.path.join(args.dir, r[1])
        pp = fp.split('/')
        pp.pop()
        fd = '/'.join(pp)
        if not os.path.exists(fd):
            os.makedirs(fd)
        req = requests.get(url, stream=True)
        with open(fp, 'wb') as f:
            for chunk in req.iter_content(chunk_size=1024):
                f.write(chunk)
                f.flush()
        f.close()

    f = open(args.dir.replace('/', '_') + '.css', 'w')
    f.write(soucecode.replace('https://fonts.gstatic.com/s/', '/%s/' % args.dir))
    f.close()
    print('DONE')


if __name__ == '__main__':
    main()
